package input

import (
	"fmt"
	"reflect"
	"strconv"
	"time"

	"gitee.com/knowgo/ego/core/function"
	"gitee.com/knowgo/ego/egoc"
)

type TimeFormatter interface {
	GetTimeFormat(egoc.TimeFormatter) string
}

func parseTime(argType *function.ArgumentTypeInfo, data interface{}) (reflect.Value, error) {
	if data == nil {
		return reflect.Zero(argType.TypeInfo.ReferenceType), nil
	}
	var err error
	timeStr, ok := data.(string)
	if argType.TimeFormat == "" {
		// 毫秒
		var ms int64
		if ok {
			ms, err = strconv.ParseInt(timeStr, 10, 64)
			if err != nil {
				return reflect.ValueOf(&time.Time{}), fmt.Errorf("time value need int64, or define time format in tag: %w", err)
			}
		} else if msFloat, ok := data.(float64); ok {
			ms = int64(msFloat)
		} else {
			// 数据类型既不是 string 也不是 float64
			return reflect.ValueOf(&time.Time{}), fmt.Errorf("time data type must be int64 or string when use millionsecond")
		}
		date := time.UnixMilli(ms)
		return reflect.ValueOf(&date), nil
	}

	if !ok {
		// 不是字符串
		return reflect.ValueOf(&time.Time{}), fmt.Errorf("time must use string type when format is setted not ms")
	}
	var timeVal time.Time
	if argType.TimeLocation == nil {
		timeVal, err = time.Parse(argType.TimeFormat, timeStr)
		if err != nil {
			return reflect.ValueOf(&time.Time{}), fmt.Errorf("time parse error: %w", err)
		}
	} else {
		timeVal, err = time.ParseInLocation(argType.TimeFormat, timeStr, argType.TimeLocation)
		if err != nil {
			return reflect.ValueOf(&time.Time{}), fmt.Errorf("time parse error: %w", err)
		}
	}
	return reflect.ValueOf(&timeVal), nil
	// timeData := reflect.ValueOf(data)
	// if timeData.Kind() != reflect.String {
	// 	return reflect.ValueOf(&time.Time{}), fmt.Errorf("time must use string type")
	// }

	// timeStr := timeData.String()
	// format := fnGetFmt(context.TimeFormatter(argType.TimeType))
	// if format == "" || format == string(context.TagMillinSecond) {
	// 	// 毫秒
	// 	msec, err := strconv.ParseInt(timeStr, 10, 64)
	// 	if err != nil {
	// 		return reflect.ValueOf(&time.Time{}), fmt.Errorf("time value need int64, or define time format in tag: %w", err)
	// 	}
	// 	date := time.UnixMilli(msec)
	// 	return reflect.ValueOf(&date), nil
	// }
	// date, err := time.Parse(format, timeStr)
	// if err != nil {
	// 	return reflect.ValueOf(&time.Time{}), fmt.Errorf("time parse error: %w", err)
	// }
	// return reflect.ValueOf(&date), nil
}
